//
//  SEGEditAdressViewController.m
//  ExcellentHome
//
//  Created by 刘山 on 16/11/18.
//  Copyright © 2016年 陈区. All rights reserved.
//

#import "SEGEditAdressViewController.h"

#import "SEGMyProfileViewCell.h"
#import "SEGPersonalButtonView.h"

#import "SEGEditAdressViewModel.h"

static NSString *SEGMyProfileViewCellIndentifier = @"_SEGMyProfileViewCellIndentifier";

@interface SEGEditAdressViewController () <UITableViewDataSource, UITableViewDelegate, UITextFieldDelegate, UITextViewDelegate>

/// 表格
@property (nonatomic, strong) UITableView *tableView;
 
/// viewModel
@property (nonatomic, strong) SEGEditAdressViewModel *viewModel;

@end

@implementation SEGEditAdressViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = kColor_bg;
    if (self.showType == EditAdressShowType_ADD || self.showType == EditAdressShowType_ADD_Order) {
        self.title = @"新建收货地址";
    } else {
        self.title = @"编辑收货地址";
    }
    [self setupUI];

    if (self.showType == EditAdressShowType_EDITE_Order) {
        [self showCustomNavigationRightButtonWithTitle:@"删除" image:nil hightlightImage:nil];
    }
}

#pragma mark - UI
- (void)setupUI {
    [self.view addSubview:self.tableView];
    [self.tableView registerClass:[SEGMyProfileViewCell class] forCellReuseIdentifier:SEGMyProfileViewCellIndentifier];
    self.tableView.backgroundColor = kColor_bg;
    [self.tableView setFrame:CGRectMake(0, 0, LYScreenWidth(), kLYScreenHeight())];
    if (LYScreenWidth() >= 320.0) self.tableView.bounces = NO;
}

#pragma mark - Event
- (void)onNavigationRightButtonClicked:(UIButton *)sender {
    @weakify(self);
    [[self.viewModel.deleteAddressCommand execute:@""] subscribeNext:^(NSString *message) {
        @strongify(self);
        [SEGAlertView showTmepMessageWithMessage:message];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self.navigationController popViewControllerAnimated:YES];
        });
    } error:^(NSError * _Nullable error) {
        [SEGAlertView showTmepMessageWithMessage:error.localizedFailureReason];
    }];
}
- (void)saveProfileClick {
    [self.tableView endEditing:YES];
    [self updateFrame];
    [self.tableView setFrame:CGRectMake(0, 0, LYScreenWidth(), kLYScreenHeight())];
    BOOL bo = NO;
    if (3 < self.viewModel.dataSourceArr.count) {
        SEGMyProfileViewCell *cell3 = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:3 inSection:0]]; // 默认选中
        bo = cell3.switchContent.on;
    }
    [self.viewModel.updateAddressCommand.executing subscribeNext:^(NSNumber * _Nullable x) {
        if (x.boolValue) {
            [SVProgressHUD show];
        } else {
            [SVProgressHUD dismiss];
        }
    }];
    @weakify(self);
    [[self.viewModel.updateAddressCommand execute:@(bo)] subscribeNext:^(RACTuple *tuple) {
        @strongify(self);
        RACTupleUnpack(SEGAddressModel *data, NSString *errorMessage) = tuple;
        [SEGAlertView showTmepMessageWithMessage:errorMessage];
    
        // 新建配送地址
        if (self.showType == EditAdressShowType_ADD || self.showType == EditAdressShowType_ADD_Order) {
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                if (self.showType == EditAdressShowType_ADD_Order) {
                    if (self.shouldGoBackAddressList) {
                        [self.navigationController popViewControllerAnimated:YES];
                    } else {
                        NSArray *arr = self.navigationController.childViewControllers;
                        [self.navigationController popToViewController:arr[arr.count - 3] animated:YES];
                        [[NSNotificationCenter defaultCenter] postNotificationName:@"AddressNotification" object:data];
                    }
                } else {
                    [self.navigationController popViewControllerAnimated:YES];
                }
            });
        }
        
        // 修改配送地址
        if (self.showType == EditAdressShowType_EDITE || self.showType == EditAdressShowType_EDITE_Order) {
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                if (self.showType == EditAdressShowType_EDITE_Order) {
                    if (self.shouldGoBackAddressList) {
                        [self.navigationController popViewControllerAnimated:YES];
                    } else {
                        NSArray *arr = self.navigationController.childViewControllers;
                        [self.navigationController popToViewController:arr[arr.count - 3] animated:YES];
                        [[NSNotificationCenter defaultCenter] postNotificationName:@"AddressNotification" object:data];
                    }
                } else {
                    [self.navigationController popViewControllerAnimated:YES];
                }
            });
        }
    } error:^(NSError * _Nullable error) {
        [SEGAlertView showTmepMessageWithMessage:error.localizedFailureReason];
    }];
}

#pragma mark - UITextFieldDelegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if ([string isEqualToString:@"\n"]) {
       [self updateFrame];
    }
    if (textField.tag == 100) { // 手机号
        NSInteger existedLength = textField.text.length;
        NSInteger selectedLength = range.length;
        NSInteger replaceLength = string.length;
        if (existedLength - selectedLength + replaceLength > 11) return NO;
    }
    if (textField.tag == 101) { // 收货人
        if ([string isEqualToString:@"\n"]) return YES;
        if ([[textField.text stringByReplacingCharactersInRange:range withString:string] length] > 20) return NO;
    }
    
    return YES;
}
- (void)textFieldDidEndEditing:(UITextField *)textField {
    if (textField.tag == 100) {
        [self.viewModel.dataSourceArr[1] setValue:textField.text forKey:@"value"];
    }
    if (textField.tag == 101) [self.viewModel.dataSourceArr[0] setValue:textField.text forKey:@"value"];
}

#pragma mark - UITextViewDelegate
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
    if ([text isEqualToString:@"\n"]) {
        [self updateFrame];
        [textView resignFirstResponder];
    }
    return YES;
}
- (void)textViewDidEndEditing:(UITextView *)textView {
    if (textView.tag == 101) [self.viewModel.dataSourceArr[0] setValue:textView.text forKey:@"value"];
    if (textView.tag == 102) [self.viewModel.dataSourceArr[2] setValue:textView.text forKey:@"value"];
}

#pragma mark - UIScrollViewDelegate
///  同来兼容小屏幕
- (void)scrollViewDidEndDragging:(UIScrollView*)scrollView willDecelerate:(BOOL)decelerate {
    [self updateFrame];
}
- (void)updateFrame {
    if (LYScreenWidth() < 375.0) {
        [self.tableView setFrame:CGRectMake(0, 0, LYScreenWidth(), kLYScreenHeight())];
    }
}

#pragma mark - KeyboardNSNotification
- (void)keyboardWillShow:(NSNotification *)notif {
    CGRect rect = [[notif.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    [self.tableView setFrame:CGRectMake(0, 0, LYScreenWidth(), kLYScreenHeight() - rect.size.height - 40)];
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView*)tableView numberOfRowsInSection:(NSInteger)section {
    return self.viewModel.dataSourceArr.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    SEGMyProfileViewCell *cell = [tableView dequeueReusableCellWithIdentifier:SEGMyProfileViewCellIndentifier];
    if (cell == nil) {
        cell = [[SEGMyProfileViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:SEGMyProfileViewCellIndentifier];
    }
    cell.indexPath = indexPath;
    if (indexPath.row < self.viewModel.dataSourceArr.count) {
        NSDictionary *dict = self.viewModel.dataSourceArr[indexPath.row];
        cell.titleLabel.text = [dict valueForKey:@"name"];
        if ([[dict valueForKey:@"key"] isEqualToString:@"1"]) { //收货人
            cell.isTextView = NO;
            cell.contentField.text = [dict valueForKey:@"value"];
            cell.contentField.delegate = self;
            cell.contentField.tag = 101;
        }else if ([[dict valueForKey:@"key"] isEqualToString:@"3"]) { //详细地址
            cell.isTextView = YES;
            cell.contentTextView.text = [dict valueForKey:@"value"];
            cell.contentTextView.delegate = self;
            cell.contentTextView.tag = 102;
        }
        else if ([[dict valueForKey:@"key"] isEqualToString:@"4"]) { //默认地址
            cell.isOrder = YES;
            cell.ContentLabel.text = [dict valueForKey:@"value"];
            [cell.switchContent setOn:[self.address.defaultType boolValue]];
        } else {
            cell.isTextView = NO;
            cell.contentField.text = [dict valueForKey:@"value"];
            cell.contentField.delegate = self;
        }
        if ([[dict valueForKey:@"key"] isEqualToString:@"2"]) { //手机号
            cell.contentField.keyboardType = UIKeyboardTypeNumberPad;
            cell.contentField.tag = 100;
        } else {
            cell.contentField.keyboardType = UIKeyboardTypeDefault;
        }
    }
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 10.0) {
        [cell layoutIfNeeded];
    }
    return cell;
}
#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return CGFLOAT_MIN;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return UITableViewAutomaticDimension;
}
- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 44;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 44 + 40 + 25;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    SEGPersonalButtonView *titleSectionbutton = [[SEGPersonalButtonView alloc] init];
    titleSectionbutton.titleBtn.layer.cornerRadius = 2;
    titleSectionbutton.titleBtn.layer.masksToBounds = YES;
    NSString* title = @"保存";
    [titleSectionbutton.titleBtn setTitle:title forState:UIControlStateNormal];
    [titleSectionbutton.titleBtn.titleLabel setFont:[UIFont systemFontOfSize:16]];
    [titleSectionbutton.titleBtn.titleLabel setTextColor:kColor_W];
    [titleSectionbutton.titleBtn setBackgroundColor:kColor_T];
    [titleSectionbutton.titleBtn addTarget:self action:@selector(saveProfileClick) forControlEvents:UIControlEventTouchUpInside];
    return titleSectionbutton;
}

#pragma mark - Getter
- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _tableView.delegate = self;
        _tableView.dataSource = self;
    }
    return _tableView;
}
//- (NSMutableArray *)segEditAddress {
//    NSMutableArray *arrM = [NSMutableArray array];
//    [arrM addObject:[NSMutableDictionary dictionaryWithDictionary:@{@"key":@"1",@"name":@"收货人",@"value":@""}]];
//    [arrM addObject:[NSMutableDictionary dictionaryWithDictionary:@{@"key":@"2",@"name":@"手机号码",@"value":@""}]];
//    [arrM addObject:[NSMutableDictionary dictionaryWithDictionary:@{@"key":@"3",@"name":@"详细地址",@"value":@""}]];
//    return arrM;
//}
- (SEGEditAdressViewModel *)viewModel {
    if (!_viewModel) _viewModel = [[SEGEditAdressViewModel alloc] initWithShowType:self.showType addressModel:self.address];
    return _viewModel;
}

@end
